﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace HostTool.ViewModel
{
    public class ViewModelHostFileEdit : ObservableObject
    {
        public ViewModelHostFileEdit()
        {
            init();
        }

        private void init()
        {
            HostFilePath = $"{Environment.GetFolderPath(Environment.SpecialFolder.System)}\\drivers\\etc\\hosts";
        }

        private string? _hostFilePath;
        public string? HostFilePath
        {
            get => _hostFilePath;
            set =>SetProperty(ref _hostFilePath, value);
        }

        private string? _hostFile;
        public string? HostFile
        {
            get => _hostFile;
            set => SetProperty(ref _hostFile, value);
        }

        public ICommand CommandLoadHostFile
        {
            get
            {
                return new RelayCommand(LoadHostFile);
            }
        }

        public ICommand CommandSaveHostFile
        {
            get
            {
                return new RelayCommand(SaveHostFile);
            }
        }


        private void LoadHostFile()
        {
            if (string.IsNullOrEmpty(HostFilePath)) {
                MessageBox.Show("host文件未路径未获取到");
                return;
            }
            HostFile = "";
            HostFile = File.ReadAllText(HostFilePath);
        }

        private void SaveHostFile()
        {
            if (string.IsNullOrEmpty(HostFile) || string.IsNullOrEmpty(HostFilePath))
            {
                MessageBox.Show("host路径或host内容为空");
                return;
            }
            try
            {
                File.WriteAllText(HostFilePath, HostFile);
                LoadHostFile();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"写入出错:{ex.Message}\r\n请用管理员身份尝试");

            }

        }

    }
}
